/* -*- coding: utf-8; tab-width: 4 -*-
vim: ts=4 noet ai */

/**
	Desktopd Rainbow Persona -- Colorful Firefox

	Copyright © 2016  Desktopd Project

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

	@license GPL-3.0+
	@file
*/

'use strict';

const matrix = require ('./matrix');


/* sRGB */

const fromLinearRGB = matrix.createTransformation3x3 ([
	[0.4124, 0.3576, 0.1805],
	[0.2126, 0.7152, 0.0722],
	[0.0193, 0.1192, 0.9502],
]);

const toLinearRGB = matrix.createTransformation3x3 ([
	[ 3.2406, -1.5372, -0.4986],
	[-0.9689,  1.8758,  0.0415],
	[ 0.0557, -0.2040,  1.0570],
]);


/**
	X, Y, Z values
	R, G, and B are in [0, 1]
*/
exports.fromRGB = (r, g, b) => {
	const [R, G, B] = [r, g, b].map (c =>
		c > 0.04045
			? Math.pow ((c + 0.055) / 1.055, 2.4)
			: c / 12.92);
	
	return fromLinearRGB (R, G, B);
};

/**
	R, G, B values
	Inverse of the above
	Note: Resulting RGB may be out of range
*/
exports.toRGB = (X, Y, Z) => {
	const [R, G, B] = toLinearRGB (X, Y, Z);
	return [R, G, B].map (c =>
		c > 0.0031308
			? 1.055 * Math.pow (c, 1 / 2.4) - 0.055
			: c * 12.92);
};
